const md5 = require("./md5.js");
let timer;

function request(url, method, params, header, successCallback, failCallback) {
  header = header || {};
  timer = setTimeout(() => {
    wx.showLoading({})
  }, 500)
  setTimeout(() => {
    wx.hideLoading()
  }, 1000);
  let time = new Date().getTime();
  let uid = wx.getStorageSync('uid') ? wx.getStorageSync('uid') : 0;
  let token = wx.getStorageSync('token') ? wx.getStorageSync('token') : 0;
  let lastParams = `?uid=${uid}&time=${time}&secret=${md5.hexMD5('71clouddangjiang' + token + time + uid)}`;
  url += lastParams;
  wx.request({
    url: url,
    data: params || {},
    method: method || 'get',
    header: header,
    success: (res) => {
      clearTimeout(timer);
      wx.hideLoading();
      if (res.data.code == 1) {
        successCallback(res.data);
      } else if (res.data.code == 0) {
        if (res.data.msg) {
          wx.showToast({
            title: res.data.msg,
            icon: 'none',
          })
        } else {
          wx.showToast({
            title: res.data.data,
            icon: 'none',
          })
        }
      } else if (res.data.code == 2) {
        wx.showToast({
          title: res.data.msg,
          icon: 'none',
        })
      } else if (res.data.code == 3) {
        wx.showToast({
          title: res.data.msg,
          icon: 'none',
        })
      }else if (res.data.code == 4) {
        wx.showToast({
          title: res.data.msg,
          icon: 'none',
        })
      }else if(res.data.code==8){
        successCallback(res.data)
      }
    },
    fail: (err) => {
      // console.log(err);
      clearTimeout(timer);
      wx.hideLoading();
      wx.showToast({
        title: '网络异常，请重试',
        icon: 'none',
        duration: 2000
      });
      failCallback(err)
    }
  });
}

export const ajax = {
  get: (url, params, header, successCallback, failCallback) => {
    request(url, 'get', params, {'content-type': 'application/json'}, successCallback, failCallback)
  },
  post: (url, params, header, successCallback, failCallback) => {
    request(url, 'post', params, {'content-type': 'application/x-www-form-urlencoded'}, successCallback, failCallback)
  }
};
